-- 串口1功能模块
-- 2021.05.07
-- Lingd
-- 福州泰诚网络科技有限公司

module(...,package.seeall)

require"utils"
require"pm"
require "tool"
require "metering"
require "k24c02"

local UART_ID,rdbuf = 1, ""

-- 处理从串口读到的数据
local function proc(data)
    if not data or string.len(data) == 0 then return end
    -- 追加到缓冲区
    rdbuf = rdbuf..data    
    --log.info("read data",tool.AsciitoHexStr(rdbuf," "))
    if metering.unpack(tool.HexStrToTable(rdbuf)) == true then
        rdbuf = ""
    end
end

-- 读取串口接收到的数据
local function read()
    local data = ""
    while true do        
        data = uart.read(UART_ID,"*l")
        if not data or string.len(data) == 0 then break end
        proc(data)
    end
end

-- 通过串口发送数据
function write(s)
    uart.write(UART_ID,unpack(s))
end

-- 读取寄存器列表
function read_reglist()
    local i = 1
    for i=1,#metering.ReadRegStep do
        sys.timerStart(metering.pack,metering.SlotTime*i,metering.ReadRegStep[i][1],metering.ReadRegStep[i][2],metering.RD,{0x01,0x00,0x00,0x00})
    end
end

-- 发送寄存器列表
function send_reglist()
    local i,j,data = 1,1,{{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00},{0x00,0x00,0x00,0x00}}
    
	local RegCRes = k24c02.ReadRegCRes()
    for i=1,#metering.SendRegStep do
        for j=1,4 do
            data[i][j] = RegCRes[(i-1)*4+j]
        end
        sys.timerStart(metering.pack,metering.SlotTime*i,metering.SendRegStep[i][1],metering.SendRegStep[i][2],metering.WR,data[i])
    end
end

-- 初始化配置
pm.wake("usart")
uart.on(UART_ID,"receive",read)
uart.setup(UART_ID, 9600, 8, uart.PAR_ODD, uart.STOP_1)

-- 初始化配置
sys.taskInit(function()
    sys.wait(1000)
    -- 广播配置系统控制寄存器
    metering.pack(metering.ID_1,metering.REG_SYSCTRL,metering.RA,{0x00,0x00,0x80,0x38})
    sys.wait(100)
    -- 设置电压电流校准值列表
    send_reglist()
    sys.wait(500)
    -- 定时获取有效值列表
    sys.timerLoopStart(read_reglist,(#metering.SendRegStep+1)*metering.SlotTime)
end)

